package redis.work;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import redis.util.CookieStore;

/**
 * @author houweitao
 * @date 2016年5月17日下午9:38:26
 */

public class Recommend {
	private static final Logger log = LoggerFactory.getLogger(Recommend.class);

	private static final String recommendUrl = "http://bbs.hupu.com/indexinfo/buddys.php";
	private static final String shihuhu = "http://bbs.hupu.com/vote-postdate-1";
	private static final String bxj = "http://bbs.hupu.com/bxj-postdate-1";
	private static final Map<String, String> cookies = CookieStore.getCookies();
	private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd a KK:mm:ss");

	public static void main(String[] args) {
		Recommend rec = new Recommend();
		rec.recommendByBBS(bxj);
		rec.recommendByUser("http://my.hupu.com/28352695");
	}

	void recommendByUser(String url) {
		String tiezi = url + "/topic";
		try {
			Document doc = Jsoup.connect(tiezi).followRedirects(true).timeout(10000)
					.userAgent(
							"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36")
					.cookies(cookies).get();
			String s = doc.select("li.selected").first().text();
			// System.out.println(s);

			int num = 0;
			String regex = "(?<=\\().*(?=\\))";
			Pattern p = Pattern.compile(regex);
			Matcher m = p.matcher(s);
			while (m.find()) {
				// System.out.println(m.group());
				num = Integer.valueOf(m.group());
			}

			num = num / 30 + 1;

			for (int i = 1; i <= num; i++) {
				String cur = url + "/topic-list-main-" + i;
				Document curDoc = Jsoup.connect(cur).followRedirects(true).timeout(10000)
						.userAgent(
								"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36")
						.cookies(cookies).get();
				Elements curTiezis = curDoc.select(".p_title");
				for (Element e : curTiezis) {
					String _url = e.select("a").attr("href");
					String _title = e.select("a").text();
					if (_url.length() > 10) {
						String help = _url.split("com")[1];
						help = help.substring(1, help.length() - 5);
						recommendSingle(help, _title);
					}
				}

			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	void recommendByBBS(String url) {
		// String str = "http://bbs.hupu.com/vote-postdate-1";

		try {
			Document doc = Jsoup.connect(url).followRedirects(true).timeout(10000)
					.userAgent(
							"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36")
					.get();

			Elements elements = doc.select("tbody").select("tr");
			for (Element e : elements) {
				String curUrl = e.attr("mid");
				// curUrl = "http://bbs.hupu.com/" + curUrl + ".html";
				String curTitle = "";

				Elements tmps = e.select("td.p_title").select("a");
				for (int i = 0; i < tmps.size(); i++) {
					String cur = tmps.get(i).text();
					if (!cur.equals("话题") && cur.length() > 2)
						curTitle = cur;
				}

				System.out.println(curUrl + ":" + curTitle);
				recommendSingle(curUrl, curTitle);
			}

		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private void recommendSingle(String id, String title) {
		String help = "http://bbs.hupu.com/" + id + ".html";

		try {
			Document doc = Jsoup.connect(help).followRedirects(true).timeout(10000)
					.userAgent(
							"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36")
					.get();
			String fid = doc.select(".bbs-hd-h1").select("h1#j_data").first().attr("fid");
			if (id.length() < 5)
				return;

			log.info("推荐：" + title + "@" + id);

			Map<String, String> params = buildData(id, title, fid);
			try {
				Document result = Jsoup.connect(recommendUrl).followRedirects(true).timeout(10000)
						.userAgent(
								"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36")
						.cookies(cookies).data(params).post();

				if (result.select("body").text().equals("1"))
					log.info("推荐成功");
				else
					log.info("之前推荐过");
			} catch (IOException e) {
				log.info("提交异常：" + e);
			}

		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

	}

	private Map<String, String> buildData(String url, String title, String fid) {

		// fid:1048
		// act:rc
		// cid:16273231
		// title:乔丹的身体素质到底什么水准，在今天看来比现在的球员都劲爆啊！
		// rmmsg:hahah
		// type:1

		Map<String, String> params = new HashMap<String, String>();
		params.put("fid", fid);
		params.put("act", "rc");
		params.put("cid", url);
		params.put("title", title);
		params.put("rmmsg", sdf.format(new Date()));
		params.put("type", "1");

		return params;
	}

}
